package com.zhonghe.active4j.filesys.controller;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zhonghe.active4j.common.controller.BaseController;
import com.zhonghe.active4j.core.annotation.Log;
import com.zhonghe.active4j.core.model.AjaxJson;
import com.zhonghe.active4j.core.model.LogType;
import com.zhonghe.active4j.core.model.PageInfo;
import com.zhonghe.active4j.core.query.QueryUtils;
import com.zhonghe.active4j.core.util.MyBeanUtils;
import com.zhonghe.active4j.core.util.ResponseUtil;
import com.zhonghe.active4j.core.util.ShiroUtils;
import com.zhonghe.active4j.filesys.entity.FileHandlerEntity;
import com.zhonghe.active4j.filesys.service.FileHandlerService;
import com.zhonghe.active4j.filesys.wrapper.FileHandlerWrapper;

import lombok.extern.slf4j.Slf4j;
/**
 * 文件处理器
 * @author gyj
 *
 */
@Controller
@RequestMapping("/filesys/filehandler")
@Slf4j
public class FileHandlerController  extends BaseController{

	@Autowired
	private FileHandlerService fileHandlerLineService;
	
	/**
	 * 跳转到列表页面
	 * @param model
	 * @return
	 */
	@RequestMapping("/list")
	public String list(Model model) {
		return "filesys/filehandler/filehandler_list.html";
	}
	
	/**
	 *  获取表格数据 树形结构
	 * @param sysUserEntity
	 * @param request
	 * @return
	 */
	@RequestMapping("/datagrid")
	@ResponseBody
	public void datagrid(FileHandlerEntity sysConfigEntity, PageInfo<FileHandlerEntity> page, HttpServletRequest request, HttpServletResponse response) {
		//拼接查询条件
		QueryWrapper<FileHandlerEntity> queryWrapper = QueryUtils.installQueryWrapper(sysConfigEntity, request.getParameterMap());
		
		//执行查询
		IPage<FileHandlerEntity> lstResult = fileHandlerLineService.page(page.getPageEntity(), queryWrapper);

		//结果处理,直接写到客户端
		ResponseUtil.write(response, new FileHandlerWrapper(lstResult).wrap());
	}
	
	/**
	 * 跳转到页面
	 * @param sysDepartEntity
	 * @param model
	 * @return
	 */
	@RequestMapping("/add")
	public String add(FileHandlerEntity sysConfigEntity, Model model) {
		if(StringUtils.isNotEmpty(sysConfigEntity.getId())) {
			FileHandlerEntity config = fileHandlerLineService.getById(sysConfigEntity.getId());
			model.addAttribute("config", config);
		}
		return "filesys/filehandler/filehandler.html";
	}
	
	/**
	 * 保存方法
	 * @param sysUserEntity
	 * @return
	 */
	@RequestMapping("/save")
	@RequiresPermissions("filesys/filehandler/add")
	@ResponseBody
	@Log(type = LogType.save, name = "保存用户信息", memo = "新增或编辑保存了用户信息")
	public AjaxJson save(FileHandlerEntity sysConfigEntity, String roleIds)  {
		AjaxJson j = new AjaxJson();
		
		try{
			//后端校验
			if(StringUtils.isEmpty(sysConfigEntity.getCode())) {
				j.setSuccess(false);
				j.setMsg("编码不能为空");
				return j;
			}
			
			if(StringUtils.isEmpty(sysConfigEntity.getName())) {
				j.setSuccess(false);
				j.setMsg("名称不能为空");
				return j;
			}
			
			if(StringUtils.isEmpty(sysConfigEntity.getStatus())) {
				j.setSuccess(false);
				j.setMsg("状态不能为空");
				return j;
			}
			
			if(StringUtils.isEmpty(sysConfigEntity.getInteractiveCode())) {
				j.setSuccess(false);
				j.setMsg("文件交互编码不能为空");
				return j;
			}
			
			//新增保存
			if(StringUtils.isEmpty(sysConfigEntity.getId())) {
				
				fileHandlerLineService.saveUser(sysConfigEntity, roleIds);
			}
			//编辑保存
			else {
				FileHandlerEntity tmp = fileHandlerLineService.getById(sysConfigEntity.getId());
				MyBeanUtils.copyBeanNotNull2Bean(sysConfigEntity, tmp);
				fileHandlerLineService.saveOrUpdateUser(tmp, roleIds);
			}
			
		}catch(Exception e) {
			log.error("保存用户信息报错，错误信息:" + e.getMessage());
			j.setSuccess(false);
			e.printStackTrace();
		}
		
		return j;
	}
	
	/**
	 *  删除操作
	 * @param sysUserEntity
	 * @return
	 */
	@RequestMapping("/delete")
	@RequiresPermissions("filesys:filehandler:delete")
	@ResponseBody
	@Log(type = LogType.del, name = "删除文件处理器", memo = "删除了文件处理器")
	public AjaxJson delete(FileHandlerEntity sysConfigEntity) {
		AjaxJson j = new AjaxJson();
		try {
			
			if(StringUtils.isNotEmpty(sysConfigEntity.getId())) {
				String userId = ShiroUtils.getSessionUserId();
				if(StringUtils.equals(userId, sysConfigEntity.getId())) {
					j.setSuccess(false);
					j.setMsg("不允许删除自身账户");
					return j;
				}
				FileHandlerEntity item = fileHandlerLineService.getById(sysConfigEntity.getId());
				if(null != item && "1".equals(item.getStatus())) {
					j.setSuccess(false);
					j.setMsg("不允许删除非禁用的数据");
					return j;
				}
				fileHandlerLineService.delete(sysConfigEntity);
			}
			
		}catch(Exception e) {
			log.error("删除文件处理器出错，错误信息:" + e.getMessage() );
			j.setSuccess(false);
			e.printStackTrace();
		}
		
		return j;
	}
	
	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@RequestMapping("batch/del")
	@ResponseBody
	@Log(type = LogType.del, name = "删除文件处理器", memo = "删除了文件处理器")
	public AjaxJson del(String ids) {
		AjaxJson j = new AjaxJson();
		try {
			//ids校验
			if(StringUtils.isEmpty(ids)) {
				j.setSuccess(false);
				j.setMsg("请选择一条记录");
			}
			//删除文件处理器
			Collection<FileHandlerEntity> listByIds = fileHandlerLineService.listByIds(Arrays.asList(ids));
			listByIds.forEach(e ->{
				String status = e.getStatus();
				if("1".equals(status)) {
					j.setSuccess(false);
					j.setMsg("存在启用的数据:【"+e.getCode()+"】");
				}
			});
			if(!j.isSuccess()) {
				return j;
			}
			fileHandlerLineService.batchDels(ids);
		}catch(Exception e) {
			log.error("删除文件处理器报错，错误信息：{}", e.getMessage());
			j.setSuccess(false);
			e.printStackTrace();
		}
		return j;
	}
	
	/**
	 * 公共弹出页面,  部门的选择
	 * @return
	 */
	@RequestMapping("/selectHandler")
	public String selectDept(Model model) {
		QueryWrapper<FileHandlerEntity> queryWrapper = new QueryWrapper<FileHandlerEntity>();
		queryWrapper.eq("STATUS", "1");
		queryWrapper.orderByDesc("UPDATE_DATE");
		//顶级父级部门
		List<FileHandlerEntity> lstParentDeparts = fileHandlerLineService.list(queryWrapper);
		
		//拼接
		StringBuffer sb = new StringBuffer();
		sb = sb.append("[");
		departContact(lstParentDeparts, sb);
		sb = sb.append("]");
		
		//传值
		model.addAttribute("treeData", sb.toString());
		
		return "common/selecthandler.html";
	}
	
	/**
	 * 采用递归的方式，拼接父子部门
	 * @param lstDeparts
	 * @param sb
	 */
	private void departContact(List<FileHandlerEntity> lstDeparts, StringBuffer sb) {
		if(null != lstDeparts && lstDeparts.size() > 0) {
			for(int i = 0; i < lstDeparts.size(); i++) {
				FileHandlerEntity depart = lstDeparts.get(i);
				//赋值树形结构
				sb = sb.append("{").append("text:").append("\"").append(depart.getCode() + "-" + depart.getName()).append("\",").append("id:").append("\"").append(depart.getId()).append("\"");
				
				if(i == lstDeparts.size() - 1) {
					sb = sb.append("}");
				}else {
					sb = sb.append("},");
				}
			}
		}
	}
}
